#include "xvideowidget.h"
#include <QPainter>
#include <opencv2/imgproc.hpp>

XVideoWidget::XVideoWidget(QWidget *parent)
    : QOpenGLWidget{parent}
{}

void XVideoWidget::do_setImage(cv::Mat mat)
{
    QImage::Format fmt = QImage::Format_RGB888;
    int pixSize = 3;
    //处理后是灰度图
    if (mat.type() == CV_8UC1) {
        fmt = QImage::Format_Grayscale8;
        pixSize = 1;
    }
    //RGB图
    if (img.isNull() || img.format() != fmt) {  //灰度图后，设置回rgb图
        delete img.bits();
        uchar* buf = new uchar[width() / 4 * 4  * height() / 4 * 4 * pixSize];
        //img为显示窗口大小（要4的倍数）
        img = QImage(buf, width() / 4 * 4, height() / 4 * 4, fmt);
    }
    //拷贝img大小的Mat
    cv::Mat des;
    cv::resize(mat, des, cv::Size(img.size().width(), img.size().height()));
    //设置图像颜色格式
    if (pixSize > 1) {
        cv::cvtColor(des, des, cv::COLOR_BGR2RGB);
    }
    //复制内存空间
    memcpy(img.bits(), des.data, des.cols * des.rows * des.elemSize());
    update();
}

void XVideoWidget::paintEvent(QPaintEvent *e)
{
    QPainter p;
    p.begin(this);
    p.drawImage(QPoint(0,0), img);
    p.end();
}

